package com.tb.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tb.mapper.StudentMapper;
import com.tb.pojo.*;
import com.tb.service.AllService;
import com.tb.service.StudentService;
import com.tb.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
public class StudentServiceImpl extends AllService implements StudentService {

    @Autowired
    private StudentMapper sm;

    @Override
    public void register(Student student) {
        /*学号拼接*/
        int count = sm.count() + 1;
        String sid = student.getCollege() + student.getClazz();
        if (count >= 10) {
            sid += count;
        } else {
            sid += "0" + count;
        }
//        System.out.println(sid);
        student.setSid(sid);
        /*生成随机盐*/
        String salt = SaltUtils.getSalt(8);
        Md5Hash md5Hash = new Md5Hash(student.getPassword(), salt, 1024);
        us.register(new User(null, student.getSid(), md5Hash.toHex(), salt, null));
        sm.register(student);
    }


    /**
     * 查询全部的学生信息
     * @param currentPage
     * @return
     */
    @Override
    public PageInfo<Student> findAll(int currentPage) {
        PageHelper.startPage(currentPage, 8);
        List<Student> studentList = sm.findAll();
        return new PageInfo<>(studentList);
    }

    /**
     * 上面方法的重载 进行条件查询
     * @param currentPage
     * @param collegeId
     * @param profession
     * @return
     */
    @Override
    public PageInfo<Student> findAll(int currentPage, int collegeId, int profession) {
        PageHelper.startPage(currentPage, 8);
        List<Student> studentList = sm.findAll(collegeId, profession);
        return new PageInfo<>(studentList);
    }

    @Override
    public Student findOne(String sid) {
        Student student = new Student();
        student.setSid(sid);
        return sm.findOne(student);
    }

    @Override
    public void modify(Student student) {
        System.out.println("old:" + student);
        String oldSid = student.getSid();
        student.setSid(student.getSid().replace(student.getSid().substring(0, 8), student.getCollege() + student.getClazz()));
        student.setProfession(student.getClazz().substring(0, 2));
        System.out.println("new" + student);
        String sid = student.getSid();
        /*先修改user表*/
        um.stuModify(sid, oldSid);
        /*再修改student表*/
        sm.modify(student);
    }
}
